<?php
/**
 * Created by PhpStorm.
 * User: zcq
 * Date: 2018/10/26
 * Time: 10:33
 */

namespace app\admin\service;


use app\admin\model\VoteData;
use app\admin\model\VoteItems;
use think\Db;
use think\helper\Time;

class VoteDataService extends BaseService
{
    public $dataModel;
    public $itemsModel;
    public function __construct()
    {
        parent::__construct();
        $this->dataModel = new VoteData();
        $this->itemsModel = new VoteItems();
    }

    /**
     * @param $voteId
     * 投票记录id
     */
    public function listPagination($voteId,$keyword)
    {
        $where = null;
        if($keyword){
            $where['b.mid|b.name'] = ['like','%'.$keyword.'%'];
        }
        if(!$where)
            $where = '1=1';
        $data['list'] = $this->dataModel
            ->alias('a')
            ->join(VoteItems::TABLE.' b','b.id=a.vote_item_id')
            ->where('a.vote_id',$voteId)
            ->where('is_del',$this->dataModel::DEL_FALSE)
            ->where($where)
            ->order('a.id desc')
            ->field('a.*,b.mid,b.name')
            ->paginate();
        $data['page'] = $data['list']->render();
        return $data;
    }



    /**
     * @param $id
     * 清空投票记录，初始化投票活动
     */
    public function initVote($id)
    {
        $items = [
            'real' =>0,
            'extra'=>0,
            'total'=>0,
            'modtime'=>time(),
        ];
        $record = [
            'is_del' => $this->dataModel::DEL_TRUE,
            'modtime' => time(),
        ];
        Db::startTrans();
        try{
            $num1 = $this->itemsModel->where('vote_id',$id)->count();
            $num2 = $this->dataModel->where('vote_id',$id)->where('is_del',$this->dataModel::DEL_FALSE)->count();
            if($num1){
                $res1 = $this->itemsModel->where('vote_id',$id)->update($items);
                if($res1 != $num1){
                    Db::rollback();
                    return dataReturn(0,'清空记录失败');
                }
            }
            if($num2){
                $res2 = $this->dataModel->where('vote_id',$id)->where('is_del',$this->dataModel::DEL_FALSE)->update($record);
                if($res2 != $num2){
                    Db::rollback();
                    return dataReturn(0,'清空记录失败');
                }
            }

            Db::commit();
            $this->clearVoteItems($id);
            return dataReturn(1,'清空记录成功');
        }catch (Exception $exception){
            Db::rollback();
            return dataReturn(0,'清空记录失败');
        }
    }

    public function count($vote,$start,$end,$order,$keyword,$itemId)
    {
        $where['vote_id'] = $where1['vote_id'] = ['eq',$vote['id']];
        $where['is_del'] = $where1['is_del'] = ['eq',$this->dataModel::DEL_FALSE];

        if($itemId)
            $where['vote_item_id'] = $where1['vote_item_id'] = ['eq',$itemId];

        if($keyword){
            $where['mobile'] = $where1['mobile'] = ['eq',$keyword];
        }

        $start = $start?strtotime($start):'';
        $end = $end?strtotime($end):'';
        if($start && $end){
            $where['addtime'] = ['between',[$start,$end]];
        }else if($start){
            $where['addtime'] = ['between',[$start,strtotime($vote['end'])]];
            // $where['addtime'] = ['>=',$start];
        }else if($end){
            $where['addtime'] = ['between',[strtotime($vote['start']),$end]];
            // $where['addtime'] = ['<=',$end];
        } else {
            $where['addtime'] = ['between',[strtotime($vote['start']),strtotime($vote['end'])]];
        }
        if($order=='asc'){
            $o = 'total asc';
        }elseif($order == 'desc'){
            $o = 'total desc';
        }else{
            $o = '';
        }

        $data['list'] = $this->dataModel
            ->where($where)
            ->field('mobile,sum(nums) as total')
            ->group('mobile')
            ->order($o)
            ->paginate();
        $data['page'] = $data['list']->render();
        //计算charts数据，按日期统计
        $data['chartData'] = [];

        $time = $start?: strtotime($vote['start']);
        $endtime = $end ?: strtotime($vote['end']);
        $i = 0;
        $category = [];
        $total = [];
        while (true){
            $start = $time + $i*3600*24;
            $end = $time + ($i+1)*3600*24 -1;
            if($start > $endtime)
                break;

            $nums = $this->dataModel
                ->where($where1)
                ->where('addtime','between',[$start,$end])
                ->sum('nums')?:0;

            $category[] = date('Y-m-d',$start);
            $total[] = $nums;
            $i++;
        }
        $data['chartData']['category'] = $category;
        $data['chartData']['total'] = $total;
        $data['total'] = array_sum($total);
//        $charts = $this->dataModel
//            ->where($where)
//            ->order('addtime asc')
//            ->field('nums,addtime')
//            ->select();
//        if($charts){
//            $first = strtotime(date('Y-m-d',$charts[0]['addtime']));
//            $end = strtotime(date('Y-m-d',$charts[count($charts)-1]['addtime']));
//            $days = ($end - $first )/(24 * 60 * 60);
//            for ($i = 0;$i<=$days;$i++){
//                $category[] = date('Y-m-d',$first);
//                $nums = 0;
//                foreach ($charts as $k=>$v){
//                    if($v['addtime'] >= $first && $v['addtime'] < ($first+24*60*60)){
//                        $nums += $v['nums'];
//                        unset($charts[$k]);
//                    }
//                }
//                $first += 24*60*60;
//                $total[] = $nums;
//            }
//            $data['chartData']['category'] = $category;
//            $data['chartData']['total'] = $total;
//        }

        return $data;
    }

    public function countList($voteId,$itemId)
    {
        $where['vote_id'] = ['eq',$voteId];
        if($itemId)
            $where['vote_item_id'] = ['eq',$itemId];

        $where['is_del'] = ['eq',0];
        $list = $this->dataModel
            ->where($where)
            ->field('mobile,sum(nums) as total')
            ->group('mobile')
            ->order('total desc')
            ->select();
        return $list;
    }

    /**
     * @param $voteId
     * @param $mobile
     * 统计某个手机投了哪些作品
     */
    public function countByMobile($voteId,$mobile)
    {
        $data['list'] = $this->dataModel
            ->alias('a')
            ->join($this->itemsModel::TABLE.' b','b.id=a.vote_item_id')
            ->where('a.vote_id',$voteId)
            ->where('a.mobile',$mobile)
            ->where('a.is_del',$this->dataModel::DEL_FALSE)
            ->field('sum(a.nums) as total,b.name,b.mid')
            ->group('a.vote_item_id')
            ->paginate();
        $data['page'] = $data['list']->render();
        return $data;
    }

    /**
     * @param $voteId
     * 获取活动的所有参与投票作品
     */
    public function getItems($voteId)
    {
        return $this->itemsModel->where('vote_id',$voteId)->order('id asc')->select();
    }

}